package com.zkca.xf.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.trello.rxlifecycle2.components.support.RxFragment;
import com.youth.banner.Banner;
import com.youth.banner.transformer.BackgroundToForegroundTransformer;
import com.zkca.xf.Constants_SP;
import com.zkca.xf.R;
import com.zkca.xf.model.javabean.Subject;
import com.zkca.xf.model.javabean.Usermesager;
import com.zkca.xf.ui.activity.personprotect.XunjianActivity;
import com.zkca.xf.ui.activity.technicalprotect.Dianhu_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.ElectriG_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.ElectricityF_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.ElectricityZ_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.FSU_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.FaceL_Activity;
import com.zkca.xf.ui.activity.technicalprotect.FireAlarm_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.FireControl_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.JingGaiNB_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.MenJin_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.SmokeNB_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.Smoke_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.Video_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.Water_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.XinHao_LActivity;
import com.zkca.xf.ui.activity.technicalprotect.ZhiLiuDian_LActivity;
import com.zkca.xf.ui.adapter.SwipAdapter;
import com.zkca.xf.ui.customview.SwipeRecyclerView;
import com.zkca.xf.ui.loader.GlideImageLoader;
import com.zkca.xf.utils.LogUtil;
import com.zkca.xf.utils.SPUtil;
import com.zkca.xf.view.OnRecyclerItemClickListener;
import com.zkca.xf.view.LogoutView;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by pc on 2018/8/6.
 * 首页
 */
public class HomeFragment extends RxFragment  {


    @BindView(R.id.banner_main)
    Banner bannerMain;
    @BindView(R.id.main_recycle)
    SwipeRecyclerView mainRecycle;
    Unbinder unbinder;
    private String userName, orgName, userHead;
    private List bannerImages, bannerTitles;
    private List<String> titles;
    ;
    private List<String> titlsId;
    private int[] images_CE = {
            R.mipmap.mj,R.mipmap.fsu, R.mipmap.xh,R.mipmap.zl};
    private int[] images = {
            R.mipmap.cszz,R.mipmap.cszz, R.mipmap.wxyg,R.mipmap.nb,R.mipmap.jg,
            R.mipmap.spjk,
            R.mipmap.zhyd, R.mipmap.zhyd2,R.mipmap.yd2,
            R.mipmap.gzdh,
            R.mipmap.xfs, R.mipmap.xhs, R.mipmap.xj};
    protected Context mContext;
   // private PersonalPresenter personalPresenter;

    private View headView;
    private ItemTouchHelper mItemTouchHelper;
    private List<Subject> datas = new ArrayList<>();
    private List<Subject> datasY = new ArrayList<>();
    private List<Subject> datasN = new ArrayList<>();
    private SwipAdapter adapter;
    private boolean isModule = false;

    private int width;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mContext = context;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        //personalPresenter = new PersonalPresenter(this, this);
        titles = Arrays.asList(getResources().getStringArray(R.array.titlsnane));

        titlsId = new ArrayList<>(Arrays.asList(getResources().getStringArray(R.array.titlsid)));

        DisplayMetrics dm = getResources().getDisplayMetrics();
        width = dm.widthPixels;

        initBanner();
        initdata();

        initRecycleview();
        return view;
    }


    //    @Override
//    protected void onPause() {
//        super.onPause();
//        XGPushClickedResult clickedResult = XGPushManager.onActivityStarted(this);
//        String  customContent= clickedResult.getCustomContent();
//    }
    @Override
    public void onDestroy() {
        super.onDestroy();

    }

    private void initdata() {
        TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(getActivity().TELEPHONY_SERVICE);
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
           // ToastUtils.show(getContext(), "请开启手机权限");
            return;
        }

        String user_id = SPUtil.getString(getContext(), Constants_SP.USER_ID, "");
        String imei = telephonyManager.getDeviceId();
        Map<String, String> map = new HashMap<>();
        map.put("userId", user_id);
        map.put("s4", imei);
        map.put("s5", "1");

       // personalPresenter.PersonalDetails(map);
    }

    private void initBanner() {
        bannerImages = new ArrayList<>();
        bannerImages.add(R.mipmap.pagethree);
        bannerImages.add(R.mipmap.pageone);
        bannerImages.add(R.mipmap.pagefive);



        bannerTitles = new ArrayList();
        bannerTitles.add("");
        bannerTitles.add("");
        bannerTitles.add("");


        bannerMain.setImages(bannerImages)
                .setImageLoader(new GlideImageLoader())
                .setBannerStyle(5)
                .setBannerTitles(bannerTitles)
                // .isAutoPlay(false)//禁止轮播
                .setDelayTime(3000)
                .setBannerAnimation(BackgroundToForegroundTransformer.class)
                .setIndicatorGravity(5)
                .start();
    }

    private void initRecycleview() {
        datas.clear();
        datasN.clear();
        datasY.clear();
        List<String> list = SPUtil.getList(getContext(), Constants_SP.MODULE);
        datas.clear();
        datasY.add(new Subject("智能门禁",images_CE[0],"0024",true));
        datasY.add(new Subject("FSU动环监控",images_CE[1],"0023",true));
        datasY.add(new Subject("信号检测",images_CE[2],"0022",true));
        datasY.add(new Subject("直流探测",images_CE[3],"0021",true));
        for (int i = 0; i < titles.size(); i++) {
            if (list.contains(titlsId.get(i))) {
                datasY.add(new Subject(titles.get(i), images[i], titlsId.get(i), true));
            } else {
                datasN.add(new Subject(titles.get(i), images[i], titlsId.get(i), false));
            }

        }
//        for (int i = 0; i < datas.size(); i++) {
//            boolean ismodule = datas.get(i).isModule();
//            if (ismodule){
//                datasY.add(datas.get(i));
//            }else {
//                datasN.add(datas.get(i));
//            }
//        }

        datas.clear();
        datas.addAll(datasY);
        datas.addAll(datasN);
        RecyclerView.LayoutManager manager = new GridLayoutManager(getContext(), 3);
        mainRecycle.setLayoutManager(manager);
        //  headView = LayoutInflater.from(mContext).inflate(R.layout.homefrag_head, null, false);    new SimpleDividerItemDecoration(getContext())
        DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL);
        dividerItemDecoration.setDrawable(ContextCompat.getDrawable(mContext,R.drawable.line_divider));//设置列表的分割线

        DividerItemDecoration dividerItemDecoration_O = new DividerItemDecoration(getContext(), DividerItemDecoration.HORIZONTAL);
        dividerItemDecoration_O.setDrawable(ContextCompat.getDrawable(mContext,R.drawable.line_divider));


        mainRecycle.addItemDecoration(dividerItemDecoration);
        mainRecycle.addItemDecoration(dividerItemDecoration_O);
//        mainRecycle.setLoadingMoreEnabled(false);
//        mainRecycle.setPullRefreshEnabled(false);
        adapter = new SwipAdapter(datas, mContext,width/3);
        mainRecycle.setAdapter(adapter);
        //mainRecycle.addHeaderView(headView);

        for (int i = 0; i < titlsId.size(); i++) {
            if (datas.get(i).isModule()) {
                LogUtil.e("启用模块ID", datas.get(i).getTitle() + "");
            } else {
                LogUtil.e("未启用模块ID", datas.get(i).getTitle() + "");
            }
        }

        mainRecycle.addOnItemTouchListener(new OnRecyclerItemClickListener(mainRecycle) {
            @Override
            public void onItemClick(RecyclerView.ViewHolder vh) {
                String position = datas.get(vh.getLayoutPosition()).getId();
                boolean ismodule = datas.get(vh.getLayoutPosition()).isModule();
                Intent intent = new Intent();
                switch (position) {
                    case "0001":
                        if (ismodule) {
                            intent.setClass(mContext, FireAlarm_LActivity.class); //火灾报警系统（城市消防远程监控）
                            //intent.setClass(mContext, Login_WuActivity.class); //火灾报警系统（城市消防远程监控）
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0002":
                        if (ismodule) {
                            intent.setClass(mContext, Smoke_LActivity.class);//烟感、手报系统（无线火灾自动报警系统）
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0011":
                        if (ismodule) {
                            intent.setClass(mContext, SmokeNB_LActivity.class);//NB烟感
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0012":
                        if (ismodule) {
                            intent.setClass(mContext, JingGaiNB_LActivity.class);//NB井盖
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0020":
                        if (ismodule) {
                            intent.setClass(mContext, FaceL_Activity.class);//NB井盖
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0021":
                        if (ismodule) {
                            intent.setClass(mContext, ZhiLiuDian_LActivity.class);//NB井盖
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0022":
                        if (ismodule) {
                            intent.setClass(mContext, XinHao_LActivity.class);//NB井盖
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0023":
                        if (ismodule) {
                            intent.setClass(mContext, FSU_LActivity.class);//NB井盖
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0024":
                        if (ismodule) {
                            intent.setClass(mContext, MenJin_LActivity.class);//NB井盖
//                            intent.putExtra("type", "yangan");
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0003":
                        if (ismodule) {
                            intent.setClass(mContext, Dianhu_LActivity.class);
                            mContext.startActivity(intent);
                            break;
                        }

                    case "0004":
                        if (ismodule) {
                            intent.setClass(mContext, Water_LActivity.class);
                            intent.putExtra("type", "shui");
                            mContext.startActivity(intent);
                        }

                        break;
                    case "0005":
                        if (ismodule) {
                            intent.setClass(mContext, FireControl_LActivity.class);//室外消防栓
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0006":
                        if (ismodule) {
                            intent.setClass(mContext, Video_LActivity.class);//视频监控系统
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0007":
                        if (ismodule) {
                            intent.setClass(mContext, ElectricityZ_LActivity.class);//智慧用电系统
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0008":
                        if (ismodule) {
                            intent.setClass(mContext, ElectricityF_LActivity.class);//智慧用电系统(法泰)
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0010":
                        if (ismodule) {
                            intent.setClass(mContext, ElectriG_LActivity.class);//智慧用电系统(国标)
                            mContext.startActivity(intent);
                        }
                        break;
                    case "0009":
                        if (ismodule) {
                            intent.setClass(mContext, XunjianActivity.class);//巡检系统
                            mContext.startActivity(intent);
                        }
                        break;
                }
            }

            @Override
            public void onItemLongClick(RecyclerView.ViewHolder vh) {
//                mItemTouchHelper.startDrag(vh);
            }
        });


//        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
//
//            /**
//             * 是否处理滑动事件 以及拖拽和滑动的方向 如果是列表类型的RecyclerView的只存在UP和DOWN，如果是网格类RecyclerView则还应该多有LEFT和RIGHT
//             * @param recyclerView
//             * @param viewHolder
//             * @return
//             */
//            @Override
//            public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//                if (recyclerView.getLayoutManager() instanceof GridLayoutManager) {
//                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN |
//                            ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
//                    final int swipeFlags = 0;
//                    return makeMovementFlags(dragFlags, swipeFlags);
//                } else {
//                    final int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN;
//                    final int swipeFlags = 0;
////                    final int swipeFlags = ItemTouchHelper.START | ItemTouchHelper.END;
//                    return makeMovementFlags(dragFlags, swipeFlags);
//                }
//            }
//
//            @Override
//            public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
//                //得到当拖拽的viewHolder的Position
//                int fromPosition = viewHolder.getAdapterPosition();
//                //拿到当前拖拽到的item的viewHolder
//                int toPosition = target.getAdapterPosition();
//                if (fromPosition < toPosition) {
//                    for (int i = fromPosition; i < toPosition; i++) {
//                        Collections.swap(datas, i, i + 1);
//                    }
//                } else {
//                    for (int i = fromPosition; i > toPosition; i--) {
//                        Collections.swap(datas, i, i - 1);
//                    }
//                }
//                adapter.notifyItemMoved(fromPosition, toPosition);
//                return true;
//            }
//
//            @Override
//            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
////                int position = viewHolder.getAdapterPosition();
////                myAdapter.notifyItemRemoved(position);
////                datas.remove(position);
//            }
//
//            /**
//             * 重写拖拽可用
//             * @return
//             */
//            @Override
//            public boolean isLongPressDragEnabled() {
//                return false;
//            }
//
//            /**
//             * 长按选中Item的时候开始调用
//             *
//             * @param viewHolder
//             * @param actionState
//             */
//            @Override
//            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
//                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
//                    viewHolder.itemView.setBackgroundColor(Color.LTGRAY);
//                }
//                super.onSelectedChanged(viewHolder, actionState);
//            }
//
//            /**
//             * 手指松开的时候还原
//             * @param recyclerView
//             * @param viewHolder
//             */
//            @Override
//            public void clearView(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
//                super.clearView(recyclerView, viewHolder);
//                viewHolder.itemView.setBackgroundColor(0);
//            }
//        });
//
//        mItemTouchHelper.attachToRecyclerView(mainRecycle);


    }

//    @Override
//    public void showProgressDialog() {
//
//    }
//
//    @Override
//    public void hideProgressDialog() {
//
//    }
//
//    @Override
//    public void showError(String msg) {
//
//    }
//
//    @Override
//    public void getPersonal(Usermesager usermesager) {
//        userName = usermesager.getData().getUserName();
//        orgName = usermesager.getData().getOrgName();
//        userHead = usermesager.getData().getAvatar();
//        SPUtil.putString(getContext(), Constants_SP.ORG_NAME, orgName);
//        SPUtil.putString(getContext(), Constants_SP.USERNAME, userName);
//        SPUtil.putString(getContext(), Constants_SP.USER_MOBILE, usermesager.getData().getMobile());
//        SPUtil.putString(getContext(), Constants_SP.USER_DEP, usermesager.getData().getDepName());
//        SPUtil.putString(getContext(), Constants_SP.USER_HEAD, userHead);
//
//
//    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
